using System.Collections;
using System.Collections.Generic;

namespace SimpleFramework
{
    public interface IResValue<T>
    {
        public T Key { get; }
    }

#if UNITY_EDITOR
    [System.Serializable]
#endif
    public class ResSimpleDict<TKey, TValue>: IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable where TValue : IResValue<TKey>
    {
#if UNITY_EDITOR
        [UnityEngine.SerializeField]
#endif
        private List<TValue> m_List;
        private Dictionary<TKey, TValue> m_Dict;

        public ResSimpleDict(int count = 32)
        {
            m_List = new List<TValue>(count);
            m_Dict = new Dictionary<TKey, TValue>(count);
        }

        public int Count
        {
            get
            {
                return m_List.Count;
            }
        }

        public TValue this[int index]
        {
            get
            {
                return m_List[index];
            }
        }

        public TValue this[TKey key]
        {
            get
            {
                return m_Dict[key];
            }

            set
            {
                m_Dict[key] = value;
            }
        }


        public void Add(TKey key, TValue value)
        {
            m_List.Add(value);
            m_Dict.Add(key, value);
        }

        public void Remove(TKey key)
        {
            m_List.Remove(m_Dict[key]);
            m_Dict.Remove(key);
        }

        public void RemoveAt(int index)
        {
            var value = m_List[index];
            m_List.RemoveAt(index);
            m_Dict.Remove(value.Key);
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            return m_Dict.TryGetValue(key, out value);
        }

        public bool ContainsKey(TKey key)
        {
            return m_Dict.ContainsKey(key);
        }

        public void Clear()
        {
            m_Dict.Clear();
            m_List.Clear();
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            return m_Dict.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return m_Dict.GetEnumerator();
        }
    }
}